$(function(){
	attachPOSPaymentTypeClick();
})

function fillPageDetail(){
	selectDisplayPaymentItemDetail();
	createtitlePayment();
}

function createtitlePayment(){
	var Tabs =getCurrentTable();
	if(Tabs == null)return;
	$('[name=tabletitle_forOrder').children().remove();
	$('[name=tabletitle_forOrder]:visible').append('<div style="display:inline-block;">'+titleTable+" "+Tabs.table.tableTitle +'</div><span>  <  </span><div name="OrderNumber" style="display:inline-block;">'+titleConfirmOrder+'</div><span style="color:#000">  <  </span><div name="OrderNumber" style="display:inline-block;color:#000">'+titlePayment+'</div>');
}

function selectDisplayPaymentItemDetail(){
	$("table[name=table_folio_item]").removeAttr("orderId");
	$("[name=table_folio_item]").find("[name=item],[name=fillItem]").remove();
	var tab = getCurrentTable();
	if(tab.OrderList == null){
		componentLoading($(".POSpaymetdetail"));
		simpleserviceWithArgs("/POSgenerateOrderService",{func:"GetPOSOrderList",gtableid:tab.posresid},function(data){
			var objArray = JSON.parse(data);
			var tab = getCurrentTable();
			tab.OrderList = objArray;
			for(var i=0;i<tab.OrderList.length;i++)
				for(var j=0;j<tab.OrderList[i].items.length;j++)
					tab.OrderList[i].items[j].refItem = getObjectFromSharedData(SharedData.Item,getCurrentTable().OrderList[i].items[j].item);
			loadFolioId(tab);
		},null);
	}
	else loadFolioId(tab);
	
	function loadFolioId(tab){
		var obj = getObjectFromSharedData(SharedData.POSReservationTable,tab.posresid);
		if(obj.displayFolioId==null||obj.displayFolioId==0)
			simpleserviceWithArgs("/POSPaymentService",{func:"SetPOSFolio",guestTableId:tab.posresid},function(data,args){
				args.obj.displayFolioId = JSON.parse(data).displayFolioId;
				closeComponentLoading($(".POSpaymetdetail"));
				fillPamentDetailTable(args.tab);
			},{tab:tab,obj:obj});
		else{
			closeComponentLoading($(".POSpaymetdetail"));
			fillPamentDetailTable(tab);
		}		
	}
	
	function fillPamentDetailTable(tab){
		var data = "<tr name='item' refid='{0}'><td>{1}</td><td class='productname'><div>{2}</div></td><td>{3}</td><td>{4}</td><td>{5}</td><td>{6}</td><td>{7}</td></tr>";
		var index=1;
		var renderList = [];
		if(tab.PaymentOrder==null){
			tab.PaymentList = [];
			tab.FromOrderList = "";
			for(var i=0;i<tab.OrderList.length;i++){
				if(!tab.OrderList[i].status) continue;
				if(tab.FromOrderList != "") tab.FromOrderList += ",";
				tab.FromOrderList+=tab.OrderList[i].id;
				for(var j=0;j<tab.OrderList[i].items.length;j++){
					if(!tab.OrderList[i].items[j].status) continue;
					var existPaymentItem = getObjectFromDataIndex(tab.PaymentList,"item",tab.OrderList[i].items[j].item);
					if(tab.OrderList[i].items[j].item==null || existPaymentItem==null){
						var tmpItem = jQuery.extend(true,{},tab.OrderList[i].items[j]);
						if(tmpItem.item==null)
							tmpItem.customId = tmpItem.id;
						delete tmpItem.id;
						tmpItem.fromOrder = [{id:tab.OrderList[i].id,displayId:tab.OrderList[i].displayId}];
						tmpItem.refId = (tmpItem.item==null)? guid():tmpItem.item;
						if(tmpItem.tax!=null)
						{
							var cloneTax = [].concat(tmpItem.tax);
							for(var k=1;k<tmpItem.amount;k++)
								for(var l=0;l<cloneTax.length;l++)
									tmpItem.tax.push(jQuery.extend(true,{},cloneTax[l]));
						}
						tab.PaymentList.push(tmpItem);
					}
					else{
						existPaymentItem.amount += tab.OrderList[i].items[j].amount;
						existPaymentItem.discount += tab.OrderList[i].items[j].discount;
						existPaymentItem.fromOrder.push({id:tab.OrderList[i].id,displayId:tab.OrderList[i].displayId});
						delete existPaymentItem.id;
						for(var k=0;k<tab.OrderList[i].items[j].tax.length;k++)
							for(var l=0;l<tab.OrderList[i].items[j].amount;l++)
								existPaymentItem.tax.push(jQuery.extend(true,{},tab.OrderList[i].items[j].tax[k]));
					}
				}
			}
			renderList = tab.PaymentList;
		}
		else
			renderList = tab.PaymentOrder;
		
		for(var i=0;i<renderList.length;i++)
		{
			var paymentItem = jQuery.extend(true,{},renderList[i]);
			if(paymentItem.refItem!=null){
				var displayPrice = (SharedData.General.incloudetax)? paymentItem.refItem.price + paymentItem.refItem.totalTax: paymentItem.refItem.price;
			}else{
				if(SharedData.General.incloudetax){
					var _tax = getSharedDataPOSTax();
					var displayPrice = customCalTax(paymentItem.price,_tax.perc,_tax.fix).totalPrice;
				}else 
					var displayPrice = paymentItem.price;
			}
			var totaltax=0;
			for(var j=0;j<paymentItem.tax.length;j++) totaltax += (paymentItem.tax[j].taxValue>0)? paymentItem.tax[j].taxValue:0;
			paymentItem.tax = [{taxValue:(totaltax/paymentItem.amount)}];
			var priceAndTax = calPriceAndTaxWithQuantity(paymentItem);
			var foliolink = "";
			if(paymentItem.fromOrder!=null)
				for(var j=0;j<paymentItem.fromOrder.length;j++){
					foliolink = (foliolink!="")? foliolink+", ":"Folio #";
					foliolink += "<span class='link' onclick='openOrderIdFromPayment("+paymentItem.fromOrder[j].id+")'>"+paymentItem.fromOrder[j].displayId+"</span>";
				}
			var foliolinktag = (paymentItem.fromOrder==null)?"":"&nbsp;&nbsp;<span class='linkColor'>("+foliolink+")</span>";
			var dataString = data.format(paymentItem.refId,
					index,
					paymentItem.title + foliolinktag,
					toCurrencyString(displayPrice),
					"<span class='link' onclick='editPOSPaymentOrderUnit($(this))'>" + paymentItem.amount + "</span>",
					"<span class='link' onclick='editPOSPaymentOrderDiscount($(this))'>" +toCurrencyString(paymentItem.discount) + "</span>",
					toCurrencyString(priceAndTax.taxPerItem * paymentItem.amount),
					toCurrencyString(priceAndTax.displayPriceTotal));
			var d = $("tr[name=item][refid]:last:visible");
			if(d.size()==0)
				$("tr[name=table_folio_header]:visible").after(dataString);
			else
				d.after(dataString);
			index++;
		}
		fillAddSuggestItem(afterSelectPaymentItem);
		$("[name=fillItem] [name=del]").remove();
		$("table[name=table_folio_item]:visible").find("[name=fillItem] .fillInputblock").focus();
		var obj = getObjectFromSharedData(SharedData.POSReservationTable,tab.posresid);
		$(".POSpaymetdetail .Orderdetail_foliotital span:last").html(obj.displayFolioId);
	}
}

function afterSelectPaymentItem(e,s){
	var item = getObjectFromDataIndex(SharedData.Item,"title",s.item.label);
	var price = item.price;
	if(SharedData.General.incloudetax)
		price += item.totalTax;
	$(this).parents("tr:first").find("[name=price]").html(toCurrencyString(price));
	$(this).parents("tr:first").attr("refid",item.id);
	
	$(this).parents("td:first").find(".searchItemOrder").css("display","none");
	$(this).parents("td:first").append("<div style='width: calc(100% - 40px)';>"+item.title+"</div>");
	
	var unit = $(this).parents("tr:first").find("[name=unit]");
	unit.focus();
	numpad(unit,null,EditPaymentUnit,this);
}

function EditPaymentUnit(el){
	if($("[name=fillItem] .searchItemOrder:visible").size()>0) {$("[name=fillItem]:visible .fillInputblock").focus(); return;}
	var tab = getCurrentTable();
	var tr = $(el).parents("tr:first");
	var item = getObjectFromSharedData(SharedData.Item,tr.attr("refid"));
	
	cloneOrderPaymentObject();
	var tmp = getObjectFromDataIndex(tab.PaymentOrder,"refId",item.id);
	var tmpAmount = tr.find('[name=unit]').val();
	var amount = (tmpAmount=="")?0:parseInt(tr.find('[name=unit]').val());
	if(tmp!=null){
		if(tmp.status)
			tmp.amount += amount;
		else{
			tmp.amount = amount;
			tmp.discount = 0;
			tmp.status = true;
			tab.EditOrder.items.push(tab.EditOrder.items.splice(tab.EditOrder.items.indexOf(tmp),1)[0]);
		}
		var tax = getSummationPOSTaxPercAndFix(tmp.refItem);
		var totalTax = customCalTax(tmp.price,tax.percent,tax.fix,tmp.discount,tmp.amount).totalTax;
		tmp.tax = [{taxValue:totalTax}];
	}
	else
		tab.PaymentOrder.push({amount:amount,
			discount:currencyStringToNumber(tr.find('[name=discount]').text()),
			item:tr.attr("refid"),
			refId:tr.attr("refid"),
			refItem: item,
			price:item.price,
			tax:[{taxValue:item.totalTax}],
			title:item.title,
			type:'fillItem',
			status:true});
	selectDisplayPaymentItemDetail();
}

function editPOSPaymentOrderUnit(dom){
	fillSimpleTextEditWithNumpad(dom,true,function(obj){
		var id = obj.dom.parents("tr:first").attr("refid");
		var tab = getCurrentTable();
		var q = obj.textbox.val();
		if(q == obj.dom.text()) return;
		cloneOrderPaymentObject();
		var obj = getObjectFromDataIndex(tab.PaymentOrder,"refId",id);
		if(obj.refItem!=null)
			var tax = getPOSTaxPercFixFromItem(obj.refItem);
		else{
			var tax = getSharedDataPOSTax();
		}
		obj.amount = parseInt(q);
		delete obj.tax;
		var tmp = customCalTax(obj.price,tax.perc,tax.fix,obj.discount,obj.amount);
		obj.tax = [{taxValue:tmp.totalTax}];
		selectDisplayPaymentItemDetail();
	},dom,true);
}

function editPOSPaymentOrderDiscount(dom){
	fillSimpleTextEdit(dom,true,function(obj){
		if(currencyStringToNumber(obj.dom.text()) == obj.textbox.val()) return;
		var id = obj.dom.parents("tr:first").attr("refid");
		var tab = getCurrentTable();
		var discount = obj.textbox.val();
		cloneOrderPaymentObject();
		var obj = getObjectFromDataIndex(tab.PaymentOrder,"refId",id);
		if(obj.refItem!=null)
			var tax = getPOSTaxPercFixFromItem(obj.refItem);
		else{
			var tax = getSharedDataPOSTax();
		}
		obj.discount = parseFloat(discount);
		delete obj.tax;
		var tmp = customCalTax(obj.price,tax.perc,tax.fix,obj.discount,obj.amount);
		obj.tax = [{taxValue:tmp.totalTax}];
		selectDisplayPaymentItemDetail();
	},dom,true);
}

function updateOrderPayment(){
	var tab = getCurrentTable();
	if(tab.PaymentOrder==null) return;
	var items = [];
	for(var i=0;i<tab.PaymentOrder.length;i++){
		if(tab.PaymentOrder[i].item!=null){
			var tmp = {item:tab.PaymentOrder[i].item,a:tab.PaymentOrder[i].amount,discount:tab.PaymentOrder[i].discount};
			items.push(tmp);
		}
		else{
			var tmp = {title:tab.PaymentOrder[i].title,price:tab.PaymentOrder[i].price,a:tab.PaymentOrder[i].amount,discount:tab.PaymentOrder[i].discount,tax:SharedData.POS.listPOSTaxString};
			if(tab.PaymentOrder[i].customId!=null) tmp.customId = tab.PaymentOrder[i].customId;
			items.push(tmp);
		}
	}
	var fromOrder = tab.FromOrderList;
	var itemsString = JSON.stringify(items);
	waitingDialog();
	simpleserviceWithArgs("/POSPaymentService",{func:"EditPaymentOrderItem",fromOrder:fromOrder,items:itemsString,gResId:tab.posresid},function(data,args){
		closeWaitingDialog();
		var objArray = JSON.parse(data);
		getObjectFromSharedData(SharedData.POSReservationTable,args.tab.posresid).money = objArray.m;
		for(var i=0;i<objArray.o.length;i++)
			for(var j=0;j<objArray.o[i].items.length;j++)
			{
				objArray.o[i].items[j].item = objArray.o[i].items[j].itemString;
				objArray.o[i].items[j].refItem = getObjectFromSharedData(SharedData.Item,objArray.o[i].items[j].item);
				delete objArray.o[i].items[j].itemString;
				delete objArray.o[i].items[j].taxString;
			}
		args.tab.OrderList = objArray.o;
		delete args.tab.PaymentOrder;
		selectDisplayPaymentItemDetail()
	},{tab:tab});
}

function cloneOrderPaymentObject(){
	var tab = getCurrentTable();
	if(tab.PaymentOrder == null){
		tab.PaymentOrder = [];
		for(var i=0;i<tab.PaymentList.length;i++)
			tab.PaymentOrder.push(jQuery.extend(true,{},tab.PaymentList[i]));
	}
}

function openOrderIdFromPayment(id){
	var tab = getCurrentTable();
	tab.pagetitle = "orderlist";
	tab.activeOrderId = id;
	switchTab();
}

function attachPOSPaymentTypeClick(){
	attachCashPaymentEvent();
	attachChequePaymentEvent();
}

function attachCashPaymentEvent(){
	$(".selectedPay").find(".selectPaymentbtn[value=Cash]").click(function(){
		var buttons = [
			{ title:"OK", callback: function(thisdialog,args){
				thisdialog.dialog("close");
				//TODO click paid
			}}
		];
		attachCancelButton(buttons);
		var args = null;
		dynamicLoadingCustomDialog($("[for=payment]"),"Cash Payment","/POS/dialog/CashPayment.jsp",buttons,CashPaymentLoadFinish,args)
	});
}
function CashPaymentLoadFinish(dialog,args){
	dialog.parents(".ui-dialog:first").css("width","auto");
	dialog.css("overflow","hidden");
	dialog.attr("type","POSPayment");
	//TODO fill dialog for init
}

function attachChequePaymentEvent(){
	$(".selectedPay").find(".selectPaymentbtn[value=Cheque]").click(function(){
		var buttons = [
			{ title:"OK", callback: function(thisdialog,args){
				thisdialog.dialog("close");
				//TODO click paid
			}}
		];
		attachCancelButton(buttons);
		var args = null;
		dynamicLoadingCustomDialog($("[for=payment]"),"title","/POS/dialog/ChequePayment.jsp",buttons,ChequePaymentLoadFinish,args)
	});
}
function ChequePaymentLoadFinish(dialog,args){
	//dialog.parents(".ui-dialog:first").css("width","auto");
	dialog.css("overflow","hidden");
	dialog.attr("type","POSPayment");
	//TODO fill dialog for init
	
}


function attachCancelButton(e){e.splice(0, 0,{title:"Cancel",callback:function(e,t){e.dialog("close")}})}